const Router = require('koa-router')
const login = new Router()
const bodyParser = require('koa-bodyparser')
const jwt = require('jsonwebtoken')
const query = require('../../utils/db')

login.use(bodyParser())

login.post('/', async ctx => {
  let name = ctx.request.body.name
  let pwd = ctx.request.body.pwd
  let sql = `SELECT * from users where account =  '${name}'`
  let data = await new Promise((resolve, reject) => {
    return query(sql, (err, data) => {
      if (err) throw err
      resolve(data)
    })
  })
  if (data.length > 0) {
    let userData = data[0]
    console.log('[ userData ]-21', userData)
    if (pwd === userData.pwd) {
      ctx.body = {
        msg: '登录成功',
        account: userData.account,
        token: userData.token
      }
    } else {
      ctx.body = {
        msg: '密码错误'
      }
    }
  } else {
    let token = jwt.sign({ name, pwd }, 'secret', { expiresIn: 3600 * 5 })
    let sql = `INSERT INTO users VALUES ( null,'${name}','${pwd}',"${token}" )`

    let msg = await new Promise((resolve, reject) => {
      return query(sql, (err, data) => {
        if (err) throw err
        let obj = {
          msg: '注册成功',
          account: name,
          token
        }
        resolve(obj)
      })
    })
    ctx.body = msg
  }
})

module.exports = login
